package com.flashcash.solu.view.login.presenter;

import android.text.TextUtils;

import com.flashcash.kotlin.data.BasicAck;
import com.flashcash.solu.R;
import com.flashcash.solu.app.base.presenter.BaseActivityPresenterImpl;
import com.flashcash.solu.bean.LoginRequestBean;
import com.flashcash.solu.bean.LoginTokenResponse;
import com.flashcash.solu.bean.UserInfoEntity;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.harvester.TraceSender;
import com.flashcash.solu.view.login.LoginActView;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.hwangjr.rxbus.RxBus;
import com.x.leo.apphelper.log.XLog;
import com.x.leo.apphelper.utils.TimeCounter;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @作者:My
 * @创建日期: 2017/6/21 14:45
 * @描述:${TODO}
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 */

public class LoginactPreImpl extends BaseActivityPresenterImpl implements LoginActPresenter {
    private static final long TIME_PERIOD = 60 * 60 * 1000;
    private static final long TIMES_TRY = 5;
    private int loginCount;
    private int smsSendTime;
    private long smsSendStartTimeStamp;

    @Override
    public void obtainSmsCode(String phoneStr) {
        if (isPermitToSendSms()) {
            new TimeCounter(60 * 1000, 1000, getTimerListener()).start();
            mUserApi.sendSms(phoneStr)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BasicAck>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {

                            //  Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();

                            XLog.INSTANCE.e("exception: ", e, 100);
                            if (isAttached) {
                                ((LoginActView) mView).onObtainSmsError(e == null ? "" : e.getMessage());
                            }
                        }

                        @Override
                        public void onNext(BasicAck responseBody) {

                            // Toast.makeText(LoginActivity.this, "" + responseBody.toString(), Toast.LENGTH_SHORT).show();
//                            XLog.INSTANCE.d("type: " + responseBody.contentType(),10);
//                            XLog.INSTANCE.d("len: " + responseBody.contentLength(),10);
                            if (isAttached && responseBody != null && !TextUtils.equals(responseBody.getCode(), "SUCCESS")) {
                                ((LoginActView) mView).onObtainSmsError(responseBody.getMessage());
                            }
                        }
                    });
        } else {
            new TimeCounter(smsSendStartTimeStamp + 60 * 60 * 1000 - System.currentTimeMillis(), 1000, getTimerListener()).start();
            XLeoToast.showMessage(R.string.show_sms_send_too_much);
        }
    }

    private TimeCounter.TimerListener getTimerListener() {
        return new TimeCounter.TimerListener() {
            @Override
            public void onFinish() {
                if (isAttached()) {
                    ((LoginActView) mView).onCounterFinish();
                }
            }

            @Override
            public void onTick(long millisUntilFinished) {
                if (isAttached()) {
                    ((LoginActView) mView).onCounterTick(millisUntilFinished);
                }
            }
        };
    }

    private boolean isPermitToSendSms() {
        if (System.currentTimeMillis() - smsSendStartTimeStamp >= TIME_PERIOD) {
            smsSendStartTimeStamp = System.currentTimeMillis();
            smsSendTime = 1;
            return true;
        } else {
            if (++smsSendTime <= TIMES_TRY) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doLogin(final LoginRequestBean loginRequestBean) {
        /**
         * Login
         */
        final LoginActView view = (LoginActView) mView;
        showLoading(null);
        mUserApi.login(loginRequestBean.smsCode,
                loginRequestBean.captchaSid,
                loginRequestBean.captcha,
                loginRequestBean.mobile,
                loginRequestBean.inviteCode)
//                .doOnNext(new Action1<LoginTokenResponse>() {
//                    @Override
//                    public void call(LoginTokenResponse loginTokenResponse) {
//                        if (TokenManager.isReSetLoanStatus) {
//                            StateUpdater.refrashDataState(FieldParamsInt.LATESTBEAN, null);
//                        }
//                    }
//                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginTokenResponse>() {
                    @Override
                    public void onCompleted() {
                        XLog.INSTANCE.d("LoginactPreImpl: " + "on complete", 5);

                    }

                    @Override
                    public void onError(Throwable e) {
                        loginCount++;
                        if (loginCount >= 2 && isAttached()) {
                            view.showGraphicCheck();
                        }
                        dismissLoading();
                        XLog.INSTANCE.d("Error: " + e.getMessage(), 5);
                        XLeoToast.showMessage(R.string.show_input_error);

                    }

                    @Override
                    public void onNext(LoginTokenResponse loginTokenResponse) {
                        loginCount = 0;
                        XLog.INSTANCE.d("token " + loginTokenResponse.getToken(), 5);
                        TokenManager.getInstance().setToken(loginTokenResponse.getToken(), 0);
                        TokenManager.getInstance().setMobile(loginRequestBean.mobile.toString());
                        dismissLoading();
                        RxBus.get().post(new EventCollection.AccoutUpdateEvent());
                        XLog.INSTANCE.d("LoginactPreImpl: " + "on next", 5);
                        XLog.INSTANCE.d("LoginactPreImpl: " + TokenManager.getInstance().getMobile(), 5);

                        if (isAttached()) {
                            XLog.INSTANCE.d("LoginactPreImpl: " + "get tent", 5);

                            mView.getBaseActivity().setResult(0, mView.getBaseActivity().getIntent());
                        }
                        if (isAttached()) {
                            XLog.INSTANCE.d("LoginactPreImpl: " + "login success", 5);
                            ((LoginActView)mView).onLoginSuccess();
                        }
                    }
                });

    }


    @Override
    public void addUserInfo(String mobile, String blackbox) {

        final LoginActView view = (LoginActView) mView;
        showLoading(null);
        mUserApi.addUserInfo(new UserInfoEntity(mobile, blackbox, TraceSender.getAndroidID(mView.getBaseActivity())))
//                .doOnNext(new Action1<LoginTokenResponse>() {
//                    @Override
//                    public void call(LoginTokenResponse loginTokenResponse) {
//                        if (TokenManager.isReSetLoanStatus) {
//                            StateUpdater.refrashDataState(FieldParamsInt.LATESTBEAN, null);
//                        }
//                    }
//                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        ((LoginActView)mView).onAddUserInfoSuccess();
                    }
                });
    }
}
